package cn.xwt.weidisk.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

/**
 * @author 薛慰涛
 */
@Component
public class MailUtils {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 验证码邮件模板
     */
    private static final String  CODE_TEMPLATE =
            "<div>" +
            "   <div style=\"height: 50px; background: #64B5F6; line-height: 50px; text-align: center\">" +
            "       邮箱验证码" +
            "   </div>" +
            "   <div style=\"margin-top: 20px\">" +
            "       您本次的验证码为" +
            "   </div>" +
            "   <div style=\"font-size: 30px; font-weight: bold;text-align: center\">" +
            "%s" +
            "   </div>" +
            "   <div>" +
            "       5分钟内有效" +
            "   </div>" +
            "</div>";

    /**
     * 验证码邮件模板
     */
    private static final String  MSG_TEMPLATE =
            "<div>" +
            "   <div style=\"height: 50px; background: #64B5F6; line-height: 50px; text-align: center\">" +
            "       管理员信息" +
            "   </div>" +
            "   <div style=\"margin-top: 20px\">" +
            "       %s" +
            "   </div>" +
            "</div>";

    @Resource
    JavaMailSender mailSender;

    /**
     * 发送验证码
     * @param to 接受邮箱
     * @param code 验证码
     * @return boolean true: 发送成功， false：发送失败
     */
    public boolean sendCode(String to, String code) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom("1817597117@qq.com");
            helper.setTo(to);
            helper.setSubject("WeiDisk邮箱验证码");
            helper.setText(String.format(CODE_TEMPLATE, code), true);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("邮件地址错误:" + to);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 发送邮件
     * @param to 接受邮箱
     * @param msg 信息
     * @return boolean true: 发送成功， false：发送失败
     */
    public boolean sendEmail(String to, String msg) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom("1817597117@qq.com");
            helper.setTo(to);
            helper.setSubject("WeiDisk管理员信息");
            helper.setText(String.format(MSG_TEMPLATE, msg), true);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("邮件地址错误:" + to);
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
